<!DOCTYPE html>
<html lang="en">

<head>
    <meta charset="UTF-8">
    <meta http-equiv="X-UA-Compatible" content="IE=edge">
    <meta name="viewport" content="width=device-width, initial-scale=1.0">
    <title>Notepad</title>

    <style>
        .region {
            position: relative;
        }

        .back {
            position: absolute;
        }
    </style>

    <!-- mui -->
    <link rel="stylesheet" href="./assets/plugins/mui/css/mui.min.css">

    <!-- bootstrap -->
    <link rel="stylesheet" href="./assets/css/bootstrap.min.css" />

    <!-- bootstrap-validate -->
    <link rel="stylesheet" href="./assets/plugins/bootstrap-validator/bootstrapValidator.min.css">

    <!-- animate.css -->
    <link rel="stylesheet" href="./assets/css/animate.min.css" />

    <!-- city-picker 省市区选择器 -->
    <link rel="stylesheet" href="./assets/plugins/city-picker/city-picker.css">

    <!-- 重置样式 -->
    <link rel="stylesheet/less" href="./assets/css/reset.less" />

    <!-- 公共样式 -->
    <link rel="stylesheet/less" href="./assets/css/common.less" />

    <!-- 页面独立的 -->
    <link rel="stylesheet/less" href="./assets/css/ContactAdd.less" />
</head>

<body>
    <!-- 信息录入 -->
    <div class="back">
        <img src="./assets/images/back.svg" alt="">
    </div>
    <div class="info">
        <h3 class="title wow fadeInUp">信息录入</h3>

        <p class="desc wow fadeInUp" data-wow-delay="200ms">
            您可在本页录入您的联系信息，录入成功后名片将会出现在首页。如需修改首页名片信息，也请新建录入，将会自动替换原有名片。
        </p>
    </div>

    <form class="contact wow fadeInUp" data-wow-delay="300ms" id="add">
        <div class="form-group">
            <label for="nickname">姓名</label>
            <input type="text" class="form-control" id="nickname" name="nickname" placeholder="请输入姓名" />
        </div>

        <div class="form-group">
            <label for="phone">手机</label>
            <input type="text" class="form-control" id="phone" name="phone" placeholder="请输入手机" />
        </div>

        <div class="form-group">
            <label for="gender">性别</label>
            <select class="form-control" id="gender">
                <option value="0">保密</option>
                <option value="1">男</option>
                <option value="2">女</option>
            </select>
        </div>

        <div class="form-group region">
            <label for="region">地区</label>
            <input type="text" class="form-control" id="region" data-toggle="city-picker" readonly placeholder="请选择地区">
        </div>

        <div class="form-group">
            <label for="type">分类</label>
            <select class="form-control" id="type">

            </select>
        </div>

        <div class="form-group">
            <label for="remark">备注</label>
            <input type="text" class="form-control" id="remark" placeholder="请输入备注" />
        </div>

        <div class="action">
            <button class="btn">提交</button>
        </div>
    </form>
</body>

</html>
<!-- 解析less的文件 -->
<script src="./assets/js/less.min.js"></script>

<!-- jquery  -->
<script src="./assets/js/jquery.min.js"></script>

<!-- mui -->
<script src="./assets/plugins/mui/js/mui.min.js"></script>

<!-- bootstrap -->
<script src="./assets/js/bootstrap.min.js"></script>

<!-- wow.js -->
<script src="./assets/js/wow.min.js"></script>

<!-- bootstrap-validator -->
<script src="./assets/plugins/bootstrap-validator/bootstrapValidator.min.js"></script>

<!-- city-picker -->
<script src="./assets/plugins/city-picker/city-picker.data.min.js"></script>
<script src="./assets/plugins/city-picker/city-picker.min.js"></script>

<!-- axios -->
<script src="./assets/plugins/axios/axios.min.js"></script>

<!-- 用axios封装的request -->
<script src="./assets/plugins/axios/request.js"></script>

<!-- cookie -->
<script src="./assets/plugins/cookie.js"></script>

<!-- helper -->
<script src="./assets/plugins/helper.js"></script>

<script>
    //实例化wow.js
    new WOW().init()

    // 检查是否已经登录
    checkLogin()

    // 读取cookie
    let business = cookie.get('business') ? JSON.parse(cookie.get('business')) : ''

    // 实例化bootstrap-validator验证表单
    $('#add').bootstrapValidator({
        // 填写配置项
        message: '表单内容不能为空',// 所有字段默认错误信息
        // 配置三种状态的图标
        feedbackIcons: {
            valid: 'glyphicon glyphicon-ok',
            invaild: 'glyphicon glyphicon-remove',
            validating: 'glyphicon glyphicon-refresh'
        },
        // 设置需要验证字段
        fields: {
            // 手机号码
            phone: {
                // 自定义验证器
                validators: {
                    // 设置该字段不能为空
                    notEmpty: {
                        message: '手机号不能为空'
                    },
                    // 设置该字段的长度
                    stringLength: {
                        min: 11,// 最小值
                        max: 11,// 最大值
                        message: '手机号必须11位'
                    },
                    // 手机号正则  输入手机号必须符合当前规则
                    regexp: {
                        // 根据工信部最新发布的手机号要求
                        regexp: /^(?:(?:\+|00)86)?1(?:(?:3[\d])|(?:4[5-79])|(?:5[0-35-9])|(?:6[5-7])|(?:7[0-8])|(?:8[\d])|(?:9[1589]))\d{8}$/,
                        message: '手机号错误'
                    }
                }
            },
            // 姓名
            nickname: {
                validators: {
                    notEmpty: {
                        message: '姓名不能为空'
                    }
                }
            }
        }
    }).on('success.form.bv', function (e) {
        // 阻止默认行为
        e.preventDefault()
    });


    // 编辑功能
    // 先获取被编辑的id
    let cardid = location.search ? parseInt(location.search.slice(4)) : ''
    console.log(cardid)
    // 判断cardid是否为空，即判断是否为编辑状态
    if (cardid) {
        Edit()
    }
    // 封装一个异步函数 如果为编辑状态才被调用
    async function Edit() {
        // 获取数据
        let params = {
            businessid: business.id,
            cardid
        }
        // 查询通讯录
        let res = await POST({
            url: 'card/card/check',
            params
        })
        console.log(res)
        if (res.code === 1) {
            // 回显数据
            $('#nickname').val(res.data.nickname)
            $('#phone').val(res.data.mobile)
            $('#gender').val(res.data.gender)
            // 获取地区
            $('#region').citypicker('reset')
            $('#region').citypicker('destroy')
            $('#region').citypicker({
                province: res.data.province_text,
                city: res.data.city_text,
                district: res.data.district_text,
            })
            $('#type').val(res.data.typeid)
            $('#remark').val(res.data.remark)
            // console.log(res.data.province)
        } else {
            // 通讯录不存在
            mui.toast(res.msg)

            // code === 0 时回退
            setTimeout(() => {
                history.back()
            }, 2000)
        }
    }

    // 表单提交事件
    $('#add').on('submit', async () => {
        // 获取表单的某个属性
        let bootstrapValidators = $('#add').data('bootstrapValidator')

        // 判断输入内容是否验证失败
        if (!bootstrapValidators.isValid()) {
            // 验证失败就不执行后面代码
            return false
        }

        // 获取需要上传的参数
        let params = {
            businessid: business.id,
            nickname: $.trim($('#nickname').val()),
            mobile: $.trim($('#phone').val()),
            gender: $.trim($('#gender').val()),
            typeid: parseInt($.trim($('#type').val())),
            // region: $.trim($('#region').val()),
            remark: $.trim($('#remark').val()),
        }

        // 分类必须填写
        if (!params.typeid || params.typeid < 0) {
            mui.toast('请选择通讯录分类')
            return false
        }

        // 获取地区码
        let citypicker = $('#region').data("citypicker")
        let code = citypicker.getCode("district") || citypicker.getCode("city") || citypicker.getCode("province")
        // 添加地区码到查询参数
        if (code) {
            params.region = code
        }
        // 发送请求 -- 如果carid存在则为编辑状态，没有则为新建状态
        if (cardid) { // 编辑状态
            params.cardid = cardid
            let res = await POST({
                url: 'card/card/edit',
                params
            })
            console.log(res)
            if (res.code === 1) {
                mui.toast(res.msg)
                setTimeout(() => {
                    location.href = 'index.html'
                }, 2000)
            }
            else {
                mui.toast(res.msg)
            }
            // mui.toast(res.msg)
        } else { // 新建状态
            let res = await POST({
                url: 'card/card/add',
                params
            })
            console.log(res)
            if (res.code === 1) {
                mui.toast(res.msg)
                setTimeout(() => {
                    location.href = 'index.html'
                }, 2000)
            }
            else {
                mui.toast(res.msg)
            }
        }

    });

    // 获取分类
    (async () => {
        let result = await POST({
            url: 'card/card/type'
        })
        console.log(result)
        if (result.code === 1) {
            let temp = '<option value="">请选择</option>'
            let TypeList = result.data
            TypeList.forEach(item => {
                temp += `
                <option value="${item.id}">${item.name}</option>`
            })
            $('#type').html(temp)
        }
    })()

    // 返回按钮
    $('.back').on('click', () => {
        history.back()
    })

</script>